import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, Pagination, TableColumnsType, TableProps } from 'antd';
import React, { useEffect, useState } from 'react';
import UploadModal from '../organizational-manage/components/upload-modal/upload-modal';
import CreateModal from './components/create-modal/create-modal';
import RepetitionModal from '../organizational-manage/components/repetition-modal/repetition-modal';
import Tables from '@/components/tables/tables';
import { GetListType } from '@/common/types';
import { formatData } from '@/utils/time';
import docService from '@/api/services/docService';
import { debounce } from 'lodash';
import useModal from '@/hooks/use-modal/useModal';
import EditModal from './components/edit-modal/edit-modal';
import PagesHeader from '@/components/pages-header';
import NotData from '@/components/NotData';
import TipsModals from '@/components/modals/TipsModals';
import { SvgIcon } from '@/components/icon';
import TipDesc from '@/components/tipDesc/tipDesc';

const DocTypeManage = () => {
  const modal = useModal('update', 'import', 'deleteModal', 'edit', 'repetition');

  // 分页信息
  const [pagingInfo, setPagingInfo] = useState({
    page: 1,
    page_size: 10,
    searchText: '',
    offset: 0,
    isPage: true,
  });

  const [pagingTotal, setPagingTotal] = useState(0);

  // 表格信息
  const [tablesValue, setTablesValue] = useState<GetListType[]>([]);

  // 删除数据
  const [isDeleteId, setIsDeleteId] = useState<string>('');

  // 删除类型 false为个体 true为批量
  const [isDeleteStatus, setIsDeleteStatus] = useState(false);

  // table选中的数据id
  const [tableSelectEdRows, setTableSelectEdRows] = useState<React.Key[]>([]);

  // 默认修改数据
  const [defaultEditValue, setDefaultEditValue] = useState<GetListType>();

  // 重复数据
  const [repetitionData, setRepetionData] = useState<string[]>([]);

  // 删除文案
  const [deleteTitle, setDeleteTitle] = useState('');

  useEffect(() => {
    getList();
  }, [pagingInfo]);

  /**
   * @description: 表格多选
   * @return {*}
   */
  const rowSelection: TableProps<GetListType>['rowSelection'] = {
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setTableSelectEdRows(newSelectedRowKeys);
    },
  };

  const columns: TableColumnsType<GetListType> = [
    {
      title: '文档类型',
      dataIndex: 'dataset_tag',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      render: (_, { createTime }) => <span>{formatData(createTime)}</span>,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      render: (_, { updateTime }) => <span>{formatData(updateTime)}</span>,
    },
    {
      title: '操作',
      key: 'action',
      width: 230,
      render: (_, record) => (
        <div className="flex">
          <a className="flex items-center !text-@brand-color" onClick={() => hanldeEditDoc(record)}>
            <SvgIcon icon="message-ic12" size="20" className="mr-1" />
            编辑
          </a>
          <a
            className="ml-6 flex items-center !text-@error-color"
            onClick={() => openDeleteModal('only', record.id)}
          >
            <SvgIcon icon="message-ic3" size="20" className="mr-1" />
            删除
          </a>
        </div>
      ),
    },
  ];

  /**
   * @description: 清除选中表格数据
   */
  const clearTableSelectEdRows = () => {
    setTableSelectEdRows([]);
  };

  /**
   * @description: 开启删除弹窗
   * @return {*}
   */
  const openDeleteModal = (type?: string, id?: string) => {
    let result: string[] = [];
    let bol = false;
    if (type === 'only') {
      result = [id as string];
      setIsDeleteId(id as string);
      bol = false;
      setIsDeleteStatus(false);
    } else {
      result = tableSelectEdRows as string[];
      bol = true;
      setIsDeleteStatus(true);
    }

    docService.listStatus({ dataset_tag_list: result }).then((res) => {
      if (res.total > 0) {
        bol
          ? setDeleteTitle(
            `选择的${result.length}个文档类型已被${res.dataset_count}个知识库使用，删除后对应知识库的文档类型会连带删除，确认删除？`,
          )
          : setDeleteTitle(
            `文档类型已被${res.dataset_count}个知识库使用，删除后对应知识库的文档类型会连带删除，确认删除？`,
          );
      } else {
        bol
          ? setDeleteTitle(`确定要删除${result.length}个文档类型?`)
          : setDeleteTitle('确定要删除文档类型?');
      }

      modal.deleteModal.open();
    });
  };

  /**
   * @description: 提交删除弹窗信息
   * @return {*}
   */
  const deleteModalSubmit = () => {
    modal.deleteModal.startLoading();
    let result: string[] = [];
    if (isDeleteStatus) {
      result = tableSelectEdRows as string[];
    } else {
      result = [isDeleteId];
    }

    docService
      .deleteList({ dataset_tag_list: result })
      .then(() => {
        if (tablesValue.length === result.length) {
          const page = pagingInfo.page - 1 > 0 ? pagingInfo.page - 1 : 1;
          const offset = (pagingInfo.page - 2) * 10 > 0 ? (pagingInfo.page - 2) * 10 : 0;

          setPagingInfo({
            ...pagingInfo,
            page,
            offset,
          });
        } else {
          getList();
        }
        setTableSelectEdRows([]);
      })
      .finally(() => {
        modal.deleteModal.stopLoading();
        modal.deleteModal.close();
      });
  };

  /**
   * @description: 提交导入弹窗信息
   * @return {*}
   */
  const uploadModalSubmit = (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    docService
      .uploadFile(formData)
      .then((res) => {
        if (res.existing_types.length > 0) {
          setRepetionData(res.existing_types);
          modal.repetition.open();
        }
        getList();
        modal.import.close();
      })
      .finally(() => {
        modal.import.stopLoading();
      });
  };

  /**
   * @description: 获取用户信息
   * @return {*}
   */
  const getList = () => {
    docService.getList(pagingInfo).then((res) => {
      setTablesValue(res.list);
      setPagingTotal(res.total);
    });
  };

  /**
   * @description: 改变页码或每页条数
   * @param {number} page 页码
   * @param {number} pageSize 每页条数
   * @return {*}
   */
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagingInfo({ ...pagingInfo, page, page_size: pageSize, offset: (page - 1) * pageSize });
  };

  const debounceSerachUser = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPagingInfo({ ...pagingInfo, searchText: e.target.value, page: 1, offset: 0 });
  };

  const debounceSearch = debounce(debounceSerachUser, 500);

  const hanldeEditDoc = (value: GetListType) => {
    setDefaultEditValue(value);
    modal.edit.open();
  };

  /**
   * @description: 创建
   * @param {string[]} value
   * @return {*}
   */
  const updateModalSubmit = (value: string[]) => {
    modal.update.startLoading();
    docService
      .createList({ dataset_tag_list: value })
      .then((res) => {
        if (res.existing_types.length > 0) {
          setRepetionData(res.existing_types);
          modal.repetition.open();
        }
        getList();
      })
      .finally(() => {
        modal.update.close();
        modal.update.stopLoading();
      });
  };

  const handleEditSubmit = (values: { dataset_tag: string }) => {
    modal.edit.startLoading();
    const data = {
      dataset_tag_list: [values.dataset_tag],
      id: defaultEditValue?.id as string,
    };

    docService
      .updateList({ ...data })
      .then((res) => {
        setTablesValue((prev) => {
          return prev.map((item) => {
            if (item.id === res._id) {
              return {
                ...item,
                id: res._id,
                dataset_tag: res.dataset_tag,
                createTime: res.createTime,
                updateTime: res.updateTime,
              };
            }
            return item;
          });
        });
        modal.edit.close();
      })
      .finally(() => {
        modal.edit.stopLoading();
      });
  };

  const repetitionSubmit = () => {
    modal.repetition.startLoading();
    docService
      .updateList({ id: null, dataset_tag_list: repetitionData })
      .then(() => {
        getList();
        modal.repetition.close();
      })
      .finally(() => {
        modal.repetition.stopLoading();
      });
  };

  return (
    // <div className="flex min-h-screen flex-col  pb-[10px] p-4 pt-5">
    <div className="flex h-full flex-col">
      <PagesHeader>
        文档类型管理
        <TipDesc title='定义和规范知识库中上传的文档类型' />
      </PagesHeader>

      <div className=" flex flex-1 flex-col rounded-default bg-[#FFF] px-5">
        <div className="my-4  flex items-center justify-between">
          {/* <div className="flex items-center">
            <div className="text-xl text-[#474C5F] ">
              {'文档类型'}
              {pagingTotal > 0 && `(${pagingTotal})`}
            </div>

            {tableSelectEdRows.length > 0 && (
              <div className="ml-6 flex items-center text-sm leading-7 text-[#1D1D1D]">
                <div>已选择{tableSelectEdRows.length}项</div>
                <a className="ml-6 !text-@brand-color" onClick={clearTableSelectEdRows}>
                  取消
                </a>
              </div>
            )}
          </div> */}
          <Input
            placeholder="搜索"
            suffix={<SvgIcon icon="work-ic6" size={16} />}
            style={{
              width: 240,
              height: '32px',
              // borderRadius: '50px',
              borderColor: '#C9CEE2',
            }}
            onChange={debounceSearch}
          />

          <div className="flex items-center">
            <div className="flex items-center">
              {/* <Button type="primary" className="!rounded-[30px]" onClick={modal.update.open}>
                新增
              </Button>
              <Button type="primary" className="mx-5 !rounded-[30px]" onClick={modal.import.open}>
                导入
              </Button> */}
              <div
                className="ml-[15px] flex h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md  border !border-@brand-color !text-@brand-color"
                onClick={modal.import.open}
              >
                <SvgIcon icon="message-ic14" size="15" className="mr-1" />
                导入
              </div>
              <div
                className="ml-[15px] flex  h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md  border !border-@brand-color !text-@brand-color"
                onClick={modal.update.open}
              >
                <SvgIcon icon="message-ic13" size="15" className="mr-1" />
                新增
              </div>

              {tableSelectEdRows.length !== 0 && (
                // <Button
                //   type="primary"
                //   danger
                //   className={`ml-[15px] mr-7 !rounded-[30px] `}
                //   onClick={() => openDeleteModal('all')}
                //   disabled={tableSelectEdRows.length === 0}
                // >
                //   <SvgIcon icon="message-ic3" size="15" className="mr-1" />
                //   删除
                // </Button>

                <div
                  className="ml-[15px]  flex h-[32px] w-[68px] cursor-pointer items-center  justify-center  rounded-md border  text-@error-color-hover"
                  onClick={() => openDeleteModal('all')}
                >
                  <SvgIcon icon="message-ic3" size="15" className="mr-1" />
                  删除
                </div>
              )}
            </div>
            {/* <Input
              placeholder="搜索"
              prefix={<SearchOutlined style={{ color: '#C9CEE2' }} />}
              style={{
                width: 200,
                height: '34px',
                // borderRadius: '50px',
                borderColor: '#C9CEE2',
              }}
              onChange={debounceSearch}
            /> */}
          </div>
        </div>

        {tablesValue.length > 0 ? (
          <div className="h-full">
            <Tables
              rowSelection={{
                type: 'checkbox',
                ...rowSelection,
                selectedRowKeys: tableSelectEdRows,
              }}
              rowKey="id"
              columns={columns}
              dataSource={tablesValue}
              pagination={false}
              // scroll={{
              //   y: 'calc(100vh - 350px)',
              // }}
              paginationProps={{
                total: pagingTotal,
                current: pagingInfo.page,
                pageSize: pagingInfo.page_size,
                onChange: handlePaginationChange,
              }}
            />
          </div>
        ) : (
          <NotData />
        )}
      </div>

      <TipsModals
        open={modal.deleteModal.isOpen}
        onOk={deleteModalSubmit}
        onCancel={modal.deleteModal.close}
        confirmLoading={modal.deleteModal.isLoading}
      >
        {/* {isDeleteStatus ? `确定要删除${tableSelectEdRows.length}个文档?` : `确定要删除文档?`} */}
        {deleteTitle}
      </TipsModals>

      <UploadModal
        open={modal.import.isOpen}
        onCancel={modal.import.close}
        onFileOk={uploadModalSubmit}
        confirmLoading={modal.import.isLoading}
      />

      <CreateModal
        open={modal.update.isOpen}
        onOk={updateModalSubmit}
        onCancel={modal.update.close}
        confirmLoading={modal.update.isLoading}
      />

      <EditModal
        open={modal.edit.isOpen}
        onCancel={modal.edit.close}
        confirmLoading={modal.edit.isLoading}
        defaultValue={defaultEditValue}
        onSubmit={handleEditSubmit}
      />

      <RepetitionModal
        open={modal.repetition.isOpen}
        onOk={repetitionSubmit}
        onCancel={modal.repetition.close}
        confirmLoading={modal.repetition.isLoading}
        repetition={repetitionData.length}
      />
    </div>
  );
};

export default DocTypeManage;
